package cn.player.utils;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import cntv.player.core.util.LogUtil;

public class AESUtil {

	public static final String PSD = "876543@!";

	/**
	 * AES加密
	 * 
	 * @param clearText
	 *            待加密明文
	 * @param password
	 *            加密的密码
	 * @return
	 */
	public static byte[] encrypt(byte[] clearText, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			
			//SecureRandom sr = new SecureRandom();//android4.1以后会有bug,用下边一句替换
			SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
			sr.setSeed(password.getBytes());
			kgen.init(128, sr);
			
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//			Cipher cipher = Cipher.getInstance("AES");// 创建密码器,android4.3以上有bug，用下边一句替换
			Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding"); 
//			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); //小米手机有问题
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			return cipher.doFinal(clearText); // 加密
		} catch (Exception e) {
			LogUtil.i("zl", "AES encrypt Exception e = " + e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * AES解密
	 * 
	 * @param clearText
	 *            待解密的密文
	 * @param password
	 *            解密的密码
	 * @return
	 */
	public static byte[] decrypt(byte[] cipherText, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
			sr.setSeed(password.getBytes());
			kgen.init(128, sr);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding"); 
//			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			return cipher.doFinal(cipherText); // 加密
		} catch (Exception e) {
			LogUtil.i("zl", "AES decrypt Exception e = " + e);
			e.printStackTrace();
		}
		return null;
	}

}
